package com.basic.ui

import android.app.Activity
import android.content.Intent
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import com.basic.util.nullOr
import kotlin.math.roundToInt

/**
 *
 * @author: Peter Liu
 * @date: 2023/6/19
 */


fun Activity?.isAvailable(): Boolean {
    return this != null && !(isFinishing || isDestroyed)
}

/**
 * Determine if keyboard is visible.
 */
const val KEYBOARD_VISIBLE_THRESHOLD_DP = 100

fun Activity.isKeyboardVisible(): Boolean {
    val activityRoot = (this.findViewById<View>(
        Window.ID_ANDROID_CONTENT
    ) as? ViewGroup)?.getChildAt(0)

    val visibleThreshold = KEYBOARD_VISIBLE_THRESHOLD_DP.dp.toDouble().roundToInt()
    val r = Rect()

    activityRoot?.getWindowVisibleDisplayFrame(r)
    val heightDiff = activityRoot?.rootView?.height.nullOr(0) - r.height()
    return heightDiff > visibleThreshold
}

fun ComponentActivity.startActivityForResult(
    intent: Intent,
    onResultOk: (Intent?) -> Unit,
    onOtherResult: ((Intent?) -> Unit)? = null
) {
    val key = getStartActivityForResultKey(intent)
    if (key.isEmpty()) {
        return
    }
    activityResultRegistry.register(
        key,
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            onResultOk.invoke(result.data)
        } else {
            onOtherResult?.invoke(result.data)
        }
    }.launch(intent)
}

internal fun getStartActivityForResultKey(intent: Intent): String {
    val key = if (!intent.action.isNullOrEmpty()) {
        intent.action
    } else if (intent.component != null) {
        intent.component.toString()
    } else if (intent.data != null) {
        intent.data.toString()
    } else {
        ""
    }
    return "startActivityForResult#$key"
}

/**
 * 设置全屏
 *
 */
fun Activity.setFullScreenFlag() {
    window.apply {
        addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
    }
}

/**
 * 取消全屏
 */
fun Activity.clearlFullScreenFlag() {
    window.apply {
        clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
    }
}